

var nowTime = function () {
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  if(month<10){
    month='0'+month;
  }
  var day = now.getDate();
  if(day<10){
    day='0'+day;
  }
  var hour = now.getHours()
  if(hour<10){
    hour='0'+hour;
  }
  var minute = now.getMinutes()
  if(minute<10){
    minute='0'+minute;
  }
  var second = now.getSeconds()
  if(second<10){
    second='0'+second;
  }
  var date = year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second;
  return date;
}
var Time = function () {
  var timestamp = Date.parse(new Date());
  return timestamp;
}
var get = function (url) {
  var promise = new Promise((resolve, reject) => {
    var that = this;
    wx.request({
      url: url,
      success: function (res) {
        resolve(res);
      },
      error: function (e) {
        reject('网络出错');
      }
    })
  });
  return promise;
}
/*点赞，防刷校验*/
var checkDate = function (value) {
  //var promise = new Promise((resolve, reject) => {
  var flag = false;
  var rmk = true;
  var rmk=true;//默认用户是存在的。
  var that = this;
  var timestamp = Date.parse(new Date());
  var userId = value.userid;//当前用户
  var key = value.key;//文章ID 
  var type = value.type;//操作类型，点赞或者评论，浏览
  var operateType = wx.getStorageSync('operateType');
  var chaTime = 12 * 60 * 60 * 1000;//间隔时间为24小时
  //var chaTime = 1 * 60 * 1000;//调试间隔时间为1分钟
 
  var checkKey = type + key;
  if ("" == operateType) { 
    const checkMsg = [];
    checkMsg.push( { 'key': checkKey, 'timestamp': timestamp });
    wx.setStorageSync('operateType', checkMsg);
    var operateType = wx.getStorageSync('operateType');
    return { 'flag': true, 'msg': '有效' };
  }
  var newoperateType=JSON.stringify(operateType);
  var caid=JSON.parse(newoperateType);
  for (let inde in caid) { 
    var obj = caid[inde];
    if (obj.key == checkKey) {
      rmk=false;
      var oldTime = obj.timestamp;
      var userTime = oldTime + chaTime;//旧时间+间隔时间，现在时间大于这个时间，说明可以继续操作
      if (userTime < timestamp) { 
         caid.splice(inde,1);
         flag = true; 
      }
    }
  } 
  if (flag||rmk) {//已经过了有效期限制或者缓存中的用户不存在就重新写缓存时间
    var msyyy = { 'key': checkKey, 'timestamp': timestamp };
    caid.push(msyyy);
    wx.setStorageSync('operateType', caid);
    var operateType = wx.getStorageSync('operateType');
    return { 'flag': true, 'msg': '有效' };
  }else{ 
      return { 'flag': false, 'msg': '请勿频繁操作。' }; 
  } 
}

module.exports = {
  nowTime: nowTime,
  Time: Time,
  get: get,
  checkDate: checkDate
}


